<template>
  <div class="approval-container">
    <el-row :gutter="20" class="equal-height-row">

      <!-- 左侧：待审批列表 -->
      <el-col :span="10">
        <el-card class="pending-list-card full-height-card">
          <template #header>
            <div class="card-header">
              <span>待审批请假申请</span>
              <div class="header-actions">
                <el-button type="primary" size="small" @click="exportApprovals">
                  导出记录
                </el-button>
                <el-button size="small" @click="showAdvancedSearch = !showAdvancedSearch">
                  {{ showAdvancedSearch ? '收起搜索' : '高级搜索' }}
                </el-button>
              </div>
            </div>
          </template>

          <!-- 基础搜索 -->
          <div class="filter-bar">
            <el-row :gutter="8">
              <el-col :span="8">
                <el-select v-model="filterForm.type" placeholder="请假类型" clearable size="small"
                  @change="handleFilterChange">
                  <el-option label="事假" value="personal" />
                  <el-option label="病假" value="sick" />
                  <el-option label="其他" value="other" />
                </el-select>
              </el-col>
              <el-col :span="8">
                <el-select v-model="filterForm.urgency" placeholder="紧急程度" clearable size="small"
                  @change="handleFilterChange">
                  <el-option label="一般" value="normal" />
                  <el-option label="紧急" value="urgent" />
                  <el-option label="非常紧急" value="critical" />
                </el-select>
              </el-col>
              <el-col :span="8">
                <el-input v-model="filterForm.studentName" placeholder="学生姓名" clearable size="small"
                  @input="handleFilterChange">
                  <template #prefix>
                    <el-icon>
                      <Search />
                    </el-icon>
                  </template>
                </el-input>
              </el-col>
            </el-row>
          </div>

          <!-- 高级搜索 -->
          <div class="advanced-search" v-if="showAdvancedSearch">
            <el-form :model="advancedForm" label-width="80px" size="small">
              <el-row :gutter="12">
                <el-col :span="8">
                  <el-form-item label="学号">
                    <el-input v-model="advancedForm.studentId" placeholder="请输入学号" clearable />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="学院">
                    <el-select v-model="advancedForm.college" placeholder="请选择学院" clearable>
                      <el-option label="数学与计算机学院" value="math" />
                      <el-option label="计算机学院" value="computer" />
                      <el-option label="其他学院" value="other" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="年级">
                    <el-select v-model="advancedForm.grade" placeholder="请选择年级" clearable>
                      <el-option label="2021级" value="2021" />
                      <el-option label="2022级" value="2022" />
                      <el-option label="2023级" value="2023" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="12">
                <el-col :span="8">
                  <el-form-item label="开始时间">
                    <el-date-picker v-model="advancedForm.startDate" type="date" placeholder="选择日期"
                      value-format="YYYY-MM-DD" clearable />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="结束时间">
                    <el-date-picker v-model="advancedForm.endDate" type="date" placeholder="选择日期"
                      value-format="YYYY-MM-DD" clearable />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="是否出校">
                    <el-select v-model="advancedForm.leaveSchool" placeholder="请选择" clearable>
                      <el-option label="是" value="是" />
                      <el-option label="否" value="否" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="12">
                <el-col :span="24">
                  <div class="search-actions">
                    <el-button type="primary" size="small" @click="handleAdvancedSearch">搜索</el-button>
                    <el-button size="small" @click="resetAdvancedSearch">重置</el-button>
                  </div>
                </el-col>
              </el-row>
            </el-form>
          </div>

          <!-- 待审批列表 -->
          <div class="pending-list" :style="pendingListStyle">
            <div v-for="item in filteredPendingList" :key="item.id" class="pending-item"
              :class="{ active: selectedApproval && selectedApproval.id === item.id }" @click="selectApproval(item)">
              <div class="pending-item-header">
                <div class="student-basic">
                  <span class="student-name">{{ item.studentName }}</span>
                  <span class="student-id">{{ item.studentId }}</span>
                </div>
                <div class="item-meta">
                  <el-tag :type="getTypeColor(item.type)" size="small">{{ getTypeText(item.type) }}</el-tag>
                  <el-tag :type="getUrgencyType(item.urgency)" size="small">{{ getUrgencyText(item.urgency) }}</el-tag>
                  <el-tag :type="getApprovalStatusType(item.approvalStatus)" size="small">{{ getApprovalStatusText(item.approvalStatus) }}</el-tag>
                  <span class="apply-time">申请时间：{{ item.applyTime }}</span>
                </div>
              </div>

              <div class="college-info">{{ item.college }}{{ item.grade }}{{ item.className }}</div>

              <div class="leave-summary">
                <div class="leave-main">
                  <span class="leave-days" v-if="item.leaveDays > 0">{{ item.leaveDays }}天</span>
                  <span class="time-range" v-if="item.startTime || item.endTime">
                    {{ item.startTime || '—' }} — {{ item.endTime || '—' }}
                  </span>
                  <span class="time-range" v-else>时间待定</span>
                </div>
                <p class="leave-reason">{{ item.reason || '—' }}</p>
              </div>

              <div class="item-footer">
                <div class="location-tags">
                  <el-tag :type="item.leaveSchool === '是' ? 'danger' : 'success'" size="small">出校：{{ item.leaveSchool
                  }}</el-tag>
                  <el-tag :type="item.leaveCity === '是' ? 'warning' : 'success'" size="small">离市：{{ item.leaveCity
                  }}</el-tag>
                  <span class="location-text">去向：{{ item.location }}</span>
                </div>
                <div class="attachment-badge">
                  <el-icon>
                    <Document />
                  </el-icon>
                  <span>材料 {{ item.attachments }}/9</span>
                </div>
              </div>
            </div>

            <div v-if="filteredPendingList.length === 0" class="empty-state">暂无符合条件的记录</div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧：审批详情/历史标签页 -->
      <el-col :span="14">
        <div class="right-column">
          <el-tabs v-model="activeRightTab" class="right-tabs">
            <el-tab-pane label="审批详情" name="detail">
              <el-card class="approval-detail-card flex-card" v-if="selectedApproval">
                <template #header>
                  <div class="detail-header">
                    <span>请假申请详情</span>
                    <el-tag :type="getApprovalStatusType(selectedApproval.approvalStatus)" size="small">
                      {{ getApprovalStatusText(selectedApproval.approvalStatus) }}
                    </el-tag>
                  </div>
                </template>

                <div class="approval-detail">
                  <!-- 顶部摘要条 -->
                  <div class="summary-bar info-card">
                    <div class="summary-left">
                      <div class="summary-name">{{ selectedApproval.studentName }}</div>
                      <div class="summary-id">{{ selectedApproval.studentId }}</div>
                    </div>
                    <div class="summary-center">
                      <el-tag :type="getTypeColor(selectedApproval.type)" size="small">{{
                        getTypeText(selectedApproval.type)
                      }}</el-tag>
                      <span class="divider" />
                      <span class="highlight">{{ selectedApproval.leaveDays }}天</span>
                      <span class="divider" />
                      <span class="time-range">{{ selectedApproval.startTime }} — {{ selectedApproval.endTime }}</span>
                    </div>
                    <div class="summary-right">
                      <el-tag :type="selectedApproval.leaveSchool === '是' ? 'danger' : 'success'" size="small">
                        是否离校：{{ selectedApproval.leaveSchool }}
                      </el-tag>

                      <el-tag :type="getApprovalStatusType(selectedApproval.approvalStatus)" size="small">
                        {{ getApprovalStatusText(selectedApproval.approvalStatus) }}
                      </el-tag>
                    </div>
                  </div>

                  <!-- 基本信息 -->
                  <el-descriptions title="基本信息" :column="2" size="small" border class="info-card">
                    <el-descriptions-item label="姓名">{{ selectedApproval.studentName }}</el-descriptions-item>
                    <el-descriptions-item label="学号">{{ selectedApproval.studentId }}</el-descriptions-item>
                    <el-descriptions-item label="请假类型">
                      <el-tag :type="getTypeColor(selectedApproval.type)" size="small">
                        {{ getTypeText(selectedApproval.type) }}
                      </el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="请假天数">
                      <span class="highlight">{{ selectedApproval.leaveDays }}天</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="开始时间">{{ selectedApproval.startTime || '—' }}</el-descriptions-item>
                    <el-descriptions-item label="结束时间">{{ selectedApproval.endTime || '—' }}</el-descriptions-item>
                  </el-descriptions>

                  <!-- 请假原因 -->
                  <el-descriptions title="请假原因" :column="1" size="small" border class="info-card">
                    <el-descriptions-item>
                      <div class="reason-content">{{ selectedApproval.reason || '—' }}</div>
                    </el-descriptions-item>
                  </el-descriptions>

                  <!-- 去向信息 -->
                  <el-descriptions title="去向信息" :column="2" size="small" border class="info-card">
                    <el-descriptions-item label="是否出校">
                      <el-tag :type="selectedApproval.leaveSchool === '是' ? 'danger' : 'success'" size="small">
                        {{ selectedApproval.leaveSchool || '—' }}
                      </el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="是否离市">
                      <el-tag :type="selectedApproval.leaveCity === '是' ? 'warning' : 'success'" size="small">
                        {{ selectedApproval.leaveCity || '—' }}
                      </el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="出校去向" :span="2">{{ selectedApproval.location || '—' }}</el-descriptions-item>
                    <el-descriptions-item label="详细地址" :span="2">{{ selectedApproval.detailAddress || '—' }}</el-descriptions-item>
                    <el-descriptions-item label="证明材料">{{ selectedApproval.attachments || 0 }}/9</el-descriptions-item>
                    <el-descriptions-item label="来源类型">{{ selectedApproval.sourceType || '—' }}</el-descriptions-item>
                  </el-descriptions>

                  <!-- 联系信息 -->
                  <el-descriptions title="联系信息" :column="2" size="small" border class="info-card">
                    <el-descriptions-item label="紧急联系人">{{ selectedApproval.emergencyContact || '—' }}</el-descriptions-item>
                    <el-descriptions-item label="联系电话">{{ selectedApproval.emergencyPhone || '—' }}</el-descriptions-item>
                  </el-descriptions>

                  <!-- 审批操作（粘性） -->
                  <el-card shadow="never" class="info-card">
                    <template #header>
                      <div class="card-title">审批操作</div>
                    </template>
                    <!-- 已撤销状态显示 -->
                    <div v-if="isRevoked" class="status-display">
                      <el-form label-width="80px">
                        <el-form-item label="审批状态">
                          <div class="status-content">
                            <el-icon class="status-icon status-icon-info"><InfoFilled /></el-icon>
                            <span class="status-text">已撤销</span>
                          </div>
                        </el-form-item>
                        <el-form-item label="状态说明">
                          <span class="status-desc">该请假申请已被撤销</span>
                        </el-form-item>
                      </el-form>
                    </div>
                    <!-- 已驳回状态显示 -->
                    <div v-else-if="isRejected" class="status-display">
                      <el-form label-width="80px">
                        <el-form-item label="审批状态">
                          <div class="status-content">
                            <el-icon class="status-icon status-icon-error"><CircleCloseFilled /></el-icon>
                            <span class="status-text">已驳回</span>
                          </div>
                        </el-form-item>
                        <el-form-item label="状态说明">
                          <span class="status-desc">该请假申请已被驳回</span>
                        </el-form-item>
                      </el-form>
                    </div>
                    <!-- 已通过，待辅导员审核状态显示（班主任视角） -->
                    <div v-else-if="isApprovedPendingCounselor" class="status-display">
                      <el-form label-width="80px">
                        <el-form-item label="审批状态">
                          <div class="status-content">
                            <el-icon class="status-icon status-icon-success"><CircleCheckFilled /></el-icon>
                            <span class="status-text">已通过，待辅导员审核</span>
                          </div>
                        </el-form-item>
                        <el-form-item label="状态说明">
                          <span class="status-desc">您已审批通过，等待辅导员审核</span>
                        </el-form-item>
                      </el-form>
                    </div>
                    <!-- 已通过状态显示 -->
                    <div v-else-if="isApprovedByCurrentUser" class="status-display">
                      <el-form label-width="80px">
                        <el-form-item label="审批状态">
                          <div class="status-content">
                            <el-icon class="status-icon status-icon-success"><CircleCheckFilled /></el-icon>
                            <span class="status-text">已通过</span>
                          </div>
                        </el-form-item>
                        <el-form-item label="状态说明">
                          <span class="status-desc">该请假申请已通过审批</span>
                        </el-form-item>
                      </el-form>
                    </div>
                    <!-- 审批操作表单 -->
                    <el-form v-else :model="approvalForm" :rules="approvalRules" ref="approvalFormRef" label-width="80px">
                      <el-form-item label="审批意见" prop="comment">
                        <el-input v-model="approvalForm.comment" type="textarea" :rows="3" placeholder="请输入审批意见"
                          maxlength="200" show-word-limit />
                      </el-form-item>
                      <el-form-item>
                        <div class="action-buttons sticky-actions">
                          <el-button type="success" @click="handleApproval('approved')"
                            :loading="approving">通过</el-button>
                          <el-button type="danger" @click="handleApproval('rejected')"
                            :loading="approving">不通过</el-button>
                          <el-button @click="handleReturn" :loading="approving">退回</el-button>
                          <el-button @click="resetApprovalForm">重置</el-button>
                        </div>
                      </el-form-item>
                    </el-form>
                  </el-card>
                </div>
              </el-card>
              <el-card class="empty-detail flex-card" v-else>
                <div class="empty-state">请选择左侧记录以查看详情</div>
              </el-card>
            </el-tab-pane>

            <el-tab-pane label="审批历史" name="history">
              <el-card class="flex-card">
                <template #header>
                  <div class="card-title">审批历史（已处理）</div>
                </template>
                <div class="processed-list">
                  <div v-for="item in processedList" :key="item.id + '-' + item.processedTime" class="pending-item"
                    @click="selectApproval(item)">
                    <div class="pending-item-header">
                      <div class="student-basic">
                        <span class="student-name">{{ item.studentName }}</span>
                        <span class="student-id">{{ item.studentId }}</span>
                      </div>
                      <div class="item-meta">
                        <el-tag :type="item.result === '通过' ? 'success' : (item.result === '退回' ? 'warning' : 'danger')"
                          size="small">{{ item.result }}</el-tag>
                        <span class="apply-time">处理时间：{{ item.processedTime }}</span>
                      </div>
                    </div>

                    <div class="college-info">{{ item.college }}{{ item.grade }}{{ item.className }}</div>

                    <div class="leave-summary">
                      <div class="leave-main">
                        <span class="leave-days">{{ item.leaveDays }}天</span>
                        <span class="time-range">{{ item.startTime }} — {{ item.endTime }}</span>
                      </div>
                      <p class="leave-reason">审批意见：{{ item.comment }}</p>
                    </div>

                    <div class="item-footer">
                      <div class="location-tags">
                        <el-tag :type="item.leaveSchool === '是' ? 'danger' : 'success'" size="small">出校：{{
                          item.leaveSchool
                        }}</el-tag>
                        <el-tag :type="item.leaveCity === '是' ? 'warning' : 'success'" size="small">离市：{{ item.leaveCity
                        }}</el-tag>
                        <span class="location-text">去向：{{ item.location }}</span>
                      </div>
                      <div class="attachment-badge">
                        <el-icon>
                          <Document />
                        </el-icon>
                        <span>材料 {{ item.attachments }}/9</span>
                      </div>
                    </div>
                  </div>

                  <div v-if="processedList.length === 0" class="empty-state">暂无处理记录</div>
                </div>
              </el-card>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-col>

    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, type CSSProperties } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Search, Document, InfoFilled, CircleCloseFilled, CircleCheckFilled } from '@element-plus/icons-vue'
import { getLeaveListByTeacherId, approveLeave, type PendingLeaveItem, type ApproveLeaveRequest } from '../../api/leave'

const approvalFormRef = ref<FormInstance>()

// 筛选表单
const filterForm = reactive({
  type: '',
  urgency: '',
  studentName: ''
})

// 审批表单
const approvalForm = reactive({
  comment: '',
  result: ''
})

const approving = ref(false)
const selectedApproval = ref<any>(null)
const activeRightTab = ref('detail')
const processedList = ref<any[]>([])

// 计算属性：判断是否已撤销
const isRevoked = computed(() => {
  if (!selectedApproval.value) return false
  return selectedApproval.value.approvalStatus === 3
})

// 计算属性：判断是否已驳回
const isRejected = computed(() => {
  if (!selectedApproval.value) return false
  return selectedApproval.value.approvalStatus === 5
})

// 计算属性：判断是否已通过但待辅导员审核（班主任视角）
const isApprovedPendingCounselor = computed(() => {
  if (!selectedApproval.value) return false
  
  const approvalStatus = selectedApproval.value.approvalStatus
  
  // 只有当状态为"待辅导员审核"（approvalStatus === 2）时才判断
  if (approvalStatus !== 2) {
    return false
  }
  
  // 获取当前用户角色
  let currentRoleId = 0
  try {
    const userInfoStr = localStorage.getItem('userInfo')
    if (userInfoStr) {
      const userInfo = JSON.parse(userInfoStr)
      currentRoleId = userInfo.roleId || 0
    }
  } catch (e) {
    return false
  }
  
  // 只有班主任（roleId === 3）才显示"已通过，待辅导员审核"
  return currentRoleId === 3
})

// 计算属性：判断当前用户是否已审批通过
const isApprovedByCurrentUser = computed(() => {
  if (!selectedApproval.value) return false
  
  const approvalStatus = selectedApproval.value.approvalStatus
  
  // approvalStatus === 3 表示已撤销，不显示"已通过"
  if (approvalStatus === 3) {
    return false
  }
  
  // approvalStatus === 5 表示已驳回，不显示"已通过"
  if (approvalStatus === 5) {
    return false
  }
  
  // approvalStatus === 2 表示待辅导员审核，对于班主任来说应该显示"已通过，待辅导员审核"（已在上面处理）
  // 对于辅导员来说，这里不应该显示"已通过"，因为还需要审批
  if (approvalStatus === 2) {
    return false
  }
  
  // approvalStatus === 4 表示请假完全通过，所有角色都显示"已通过"
  if (approvalStatus === 4) {
    return true
  }
  
  // approvalStatus === 6 表示已销假，显示"已通过"
  if (approvalStatus === 6) {
    return true
  }
  
  return false
})

// 表单验证规则
const approvalRules: FormRules = {
  comment: [
    { required: true, message: '请输入审批意见', trigger: 'blur' }
  ]
}


// 待审批列表数据
const pendingList = ref<any[]>([])

// 计算属性：筛选后的待审批列表
const filteredPendingList = computed(() => {
  // 接口已经根据教师ID返回了相关的请假申请，后端已经做了过滤
  // 前端只需要根据用户输入的筛选条件进行过滤
  return pendingList.value.filter(item => {
    // 筛选条件：请假类型
    if (filterForm.type && item.type !== filterForm.type) return false
    // 筛选条件：紧急程度
    if (filterForm.urgency && item.urgency !== filterForm.urgency) return false
    // 筛选条件：学生姓名
    if (filterForm.studentName && !item.studentName.includes(filterForm.studentName)) return false
    return true
  })
})

// 动态样式
// 动态样式
const pendingListStyle = computed<CSSProperties>(() => ({
  maxHeight: 'calc(100vh - 200px)',
  overflowY: 'auto'
}))

// 方法：获取请假类型文本
const getTypeText = (type: string): string => {
  const typeMap: Record<string, string> = {
    personal: '事假',
    sick: '病假',
    other: '其他'
  }
  return typeMap[type] || '未知'
}

// 方法：获取请假类型对应的颜色
const getTypeColor = (type: string): string => {
  const colorMap: Record<string, string> = {
    personal: 'primary',
    sick: 'warning',
    other: 'info'
  }
  return colorMap[type] || 'default'
}

// 方法：获取紧急程度文本
const getUrgencyText = (urgency: string): string => {
  const urgencyMap: Record<string, string> = {
    normal: '一般',
    urgent: '紧急',
    critical: '非常紧急'
  }
  return urgencyMap[urgency] || '未知'
}

// 方法：获取紧急程度对应的标签类型
const getUrgencyType = (urgency: string): string => {
  const typeMap: Record<string, string> = {
    normal: 'info',
    urgent: 'warning',
    critical: 'danger'
  }
  return typeMap[urgency] || 'default'
}

// 方法：获取审批状态文本
const getApprovalStatusText = (approvalStatus: number | undefined): string => {
  if (approvalStatus === undefined || approvalStatus === null) {
    return '待审批'
  }
  const statusMap: Record<number, string> = {
    0: '待审批',
    1: '待班主任审核',
    2: '待辅导员审核',
    3: '已撤销',
    4: '已批准',
    5: '审批驳回',
    6: '已销假'
  }
  return statusMap[approvalStatus] || '未知状态'
}

// 方法：获取审批状态对应的标签类型
const getApprovalStatusType = (approvalStatus: number | undefined): string => {
  if (approvalStatus === undefined || approvalStatus === null) {
    return 'info'
  }
  const typeMap: Record<number, string> = {
    0: 'info',
    1: 'warning', // 待班主任审核
    2: 'warning', // 待辅导员审核
    3: 'info',    // 已撤销
    4: 'success', // 已批准
    5: 'danger',  // 审批驳回
    6: 'success'  // 已销假
  }
  return typeMap[approvalStatus] || 'info'
}

// 方法：选择审批申请
const selectApproval = (item: any) => {
  selectedApproval.value = item
  resetApprovalForm()
  activeRightTab.value = 'detail'
}

// 方法：重置审批表单
const resetApprovalForm = () => {
  approvalForm.comment = ''
  approvalForm.result = ''
  if (approvalFormRef.value) {
    approvalFormRef.value.resetFields()
  }
}

// 方法：处理审批
const handleApproval = async (result: string) => {
  if (!selectedApproval.value) return

  try {
    await approvalFormRef.value?.validate()

    const confirmMessage = result === 'approved' ? '批准' : '拒绝'
    await ElMessageBox.confirm(
      `确定要${confirmMessage}此请假申请吗？`,
      '确认操作',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    )

    approving.value = true

    // 获取当前用户信息
    const userInfoStr = localStorage.getItem('userInfo')
    if (!userInfoStr) {
      ElMessage.warning('请先登录')
      approving.value = false
      return
    }

    const userInfo = JSON.parse(userInfoStr)
    const roleId = userInfo.roleId

    if (!roleId) {
      ElMessage.warning('无法获取用户角色信息，请重新登录')
      approving.value = false
      return
    }

    // 获取请假ID
    const leaveId = selectedApproval.value.id
    if (!leaveId) {
      ElMessage.error('无法获取请假申请ID')
      approving.value = false
      return
    }

    // 构建审批请求数据
    const approveData: ApproveLeaveRequest = {
      leaveId: leaveId,
      approverRole: roleId, // 班主任的roleId是3
      comment: approvalForm.comment || '',
      approved: result === 'approved' // true表示通过，false表示拒绝
    }

    // 调用审批接口
    const response = await approveLeave(approveData)

    if (response.code === '200') {
      ElMessage.success(`已成功${confirmMessage}申请`)
      // 记录到已处理列表
      processedList.value.unshift({
        ...selectedApproval.value,
        result: confirmMessage,
        comment: approvalForm.comment,
        processedTime: new Date().toLocaleString()
      })
      // 从待审批移除
      pendingList.value = pendingList.value.filter(item => item.id !== selectedApproval.value.id)
      selectedApproval.value = null
      resetApprovalForm()
      // 刷新待审批列表以确保数据同步
      await fetchPendingLeaveList()
      // 切换到历史页查看刚处理的记录
      activeRightTab.value = 'history'
    } else {
      ElMessage.error(response.msg || '审批失败，请重试')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('审批失败:', error)
      ElMessage.error('审批失败，请重试')
    }
  } finally {
    approving.value = false
  }
}

// 方法：处理退回
const handleReturn = async () => {
  if (!selectedApproval.value) return

  try {
    await ElMessageBox.confirm('确定要退回此申请吗？', '确认退回', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    approving.value = true

    // 获取当前用户信息
    const userInfoStr = localStorage.getItem('userInfo')
    if (!userInfoStr) {
      ElMessage.warning('请先登录')
      approving.value = false
      return
    }

    const userInfo = JSON.parse(userInfoStr)
    const roleId = userInfo.roleId

    if (!roleId) {
      ElMessage.warning('无法获取用户角色信息，请重新登录')
      approving.value = false
      return
    }

    // 获取请假ID
    const leaveId = selectedApproval.value.id
    if (!leaveId) {
      ElMessage.error('无法获取请假申请ID')
      approving.value = false
      return
    }

    // 构建审批请求数据（退回使用 approved: false）
    const approveData: ApproveLeaveRequest = {
      leaveId: leaveId,
      approverRole: roleId, // 班主任的roleId是3
      comment: approvalForm.comment || '退回',
      approved: false // 退回视为拒绝
    }

    // 调用审批接口
    const response = await approveLeave(approveData)

    if (response.code === '200') {
      ElMessage.success('申请已退回')
      // 写入已处理列表（退回）
      processedList.value.unshift({
        ...selectedApproval.value,
        result: '退回',
        comment: approvalForm.comment || '退回',
        processedTime: new Date().toLocaleString()
      })
      // 从待审批移除
      pendingList.value = pendingList.value.filter(item => item.id !== selectedApproval.value.id)
      selectedApproval.value = null
      resetApprovalForm()
      // 刷新待审批列表以确保数据同步
      await fetchPendingLeaveList()
      activeRightTab.value = 'history'
    } else {
      ElMessage.error(response.msg || '退回失败，请重试')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('退回失败:', error)
      ElMessage.error('退回失败，请重试')
    }
  } finally {
    approving.value = false
  }
}

// 方法：导出审批记录
const exportApprovals = () => {
  ElMessage.info('导出审批记录功能待实现')
}

// 方法：处理筛选条件变化
const handleFilterChange = () => {
  // 筛选逻辑已在computed属性中实现
}

// 高级搜索相关
const showAdvancedSearch = ref(false)
const advancedForm = reactive({
  studentId: '',
  college: '',
  grade: '',
  startDate: '',
  endDate: '',
  leaveSchool: ''
})


// 高级搜索方法
const handleAdvancedSearch = () => {
  // 实现高级搜索逻辑
  ElMessage.info('高级搜索功能待实现')
}

const resetAdvancedSearch = () => {
  Object.assign(advancedForm, {
    studentId: '',
    college: '',
    grade: '',
    startDate: '',
    endDate: '',
    leaveSchool: ''
  })
}
// 获取待审批请假申请列表
const fetchPendingLeaveList = async () => {
  try {
    // 获取登录时存储的用户信息
    const userInfoStr = localStorage.getItem('userInfo')
    if (!userInfoStr) {
      ElMessage.warning('请先登录')
      return
    }

    const userInfo = JSON.parse(userInfoStr)
    const userId = userInfo.userId || userInfo.id

    if (!userId) {
      ElMessage.warning('无法获取用户ID，请重新登录')
      return
    }

    // 调用根据教师ID获取请假申请列表接口
    const response = await getLeaveListByTeacherId(userId)
    const responseCode = String(response.code)

    if (responseCode === '200' || responseCode === '0') {
      const leaveList = response.data || []

      // 将接口返回的数据映射到 pendingList
      pendingList.value = leaveList.map((item: PendingLeaveItem) => {
        // 转换请假类型：1 -> 病假, 2 -> 事假
        let typeText = 'other'
        if (item.leaveType === 1) {
          typeText = 'sick'
        } else if (item.leaveType === 2) {
          typeText = 'personal'
        }

        // 转换紧急程度：1 -> normal, 2 -> urgent
        let urgencyText = 'normal'
        if (item.urgencyLevel === 2) {
          urgencyText = 'urgent'
        }

        // 计算请假天数
        let leaveDays = 0
        if (item.startTime && item.endTime) {
          try {
            const start = new Date(item.startTime)
            const end = new Date(item.endTime)
            const diffTime = end.getTime() - start.getTime()
            leaveDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24) * 10) / 10 // 保留一位小数
          } catch (e) {
            leaveDays = 0
          }
        }

        // 格式化时间
        let startTimeText = ''
        let endTimeText = ''
        if (item.startTime) {
          try {
            const start = new Date(item.startTime)
            startTimeText = start.toLocaleString('zh-CN', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit',
              hour: '2-digit',
              minute: '2-digit',
              hour12: false
            }).replace(/\//g, '-')
          } catch (e) {
            startTimeText = item.startTime || ''
          }
        }
        if (item.endTime) {
          try {
            const end = new Date(item.endTime)
            endTimeText = end.toLocaleString('zh-CN', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit',
              hour: '2-digit',
              minute: '2-digit',
              hour12: false
            }).replace(/\//g, '-')
          } catch (e) {
            endTimeText = item.endTime || ''
          }
        }

        // 格式化申请时间（使用 createTime）
        let applyTimeText = ''
        if (item.createTime) {
          try {
            const applyTime = new Date(item.createTime)
            applyTimeText = applyTime.toLocaleString('zh-CN', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit',
              hour: '2-digit',
              minute: '2-digit',
              hour12: false
            }).replace(/\//g, '-')
          } catch (e) {
            applyTimeText = ''
          }
        } else if (item.startTime) {
          // 如果没有 createTime，使用 startTime 作为后备
          try {
            const applyTime = new Date(item.startTime)
            applyTimeText = applyTime.toLocaleString('zh-CN', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit',
              hour: '2-digit',
              minute: '2-digit',
              hour12: false
            }).replace(/\//g, '-')
          } catch (e) {
            applyTimeText = ''
          }
        }

        // 转换去向
        let leaveSchool = '否'
        let leaveCity = '否'
        let locationText = ''
        let detailAddressText = ''
        if (item.destinationType === 1) {
          leaveSchool = '否'
          locationText = '校内'
        } else if (item.destinationType === 2) {
          leaveSchool = '是'
          locationText = item.offCampusAddress || '校外'
          detailAddressText = item.offCampusAddress || ''
        }

        // 计算附件数量（如果有证明材料URL）
        let attachmentsCount = 0
        if (item.proofMaterialUrl && item.proofMaterialUrl !== 'null' && item.proofMaterialUrl !== 'string') {
          attachmentsCount = 1
        }

        return {
          id: item.id || Date.now(),
          studentName: item.studentName || '',
          studentId: item.studentNum || item.studentId || '',
          college: '', // 需要从学生信息接口获取
          grade: '', // 需要从学生信息接口获取
          className: '', // 需要从学生信息接口获取
          phone: '', // 需要从学生信息接口获取
          type: typeText,
          urgency: urgencyText,
          academicYear: '', // 需要从系统配置获取
          semester: '', // 需要从系统配置获取
          leaveNature: item.leaveType === 1 ? '因病请假' : '因私请假',
          leaveDays: leaveDays,
          sourceType: '学生申请',
          leaveEvent: '',
          reason: item.reason || '',
          startTime: startTimeText,
          endTime: endTimeText,
          leaveSchool: leaveSchool,
          leaveCity: leaveCity,
          location: locationText,
          detailAddress: detailAddressText,
          emergencyContact: item.emergencyContact || '',
          emergencyPhone: item.emergencyPhone || '',
          attachments: attachmentsCount,
          applyTime: applyTimeText,
          familyMembers: [], // 需要从学生信息接口获取
          approvalStatus: item.approvalStatus !== undefined ? item.approvalStatus : 0, // 保存审批状态
          headTeacherComment: item.headTeacherComment || null, // 班主任评论
          counselorComment: item.counselorComment || null, // 辅导员评论
          collegeComment: item.collegeComment || null // 院级评论
        }
      })

      // 初始化选中第一条
      if (pendingList.value.length > 0) {
        selectedApproval.value = pendingList.value[0]
      }
    } else {
      ElMessage.error(response.msg || '获取待审批列表失败')
    }
  } catch (error) {
    ElMessage.error('获取待审批列表失败，请稍后重试')
  }
}

onMounted(() => {
  fetchPendingLeaveList()
})
</script>

<style scoped>
.approval-container {
  padding: 20px;
  background: #f5f7fa;
  height: calc(90vh - 40px);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.equal-height-row {
  flex: 1;
  min-height: 0;
  display: flex;
}

.full-height-card {
  height: 65%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.full-height-card :deep(.el-card__body) {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 16px;
  overflow: hidden;
  min-height: 0;
}

.pending-list {
  flex: 1;
  overflow-y: auto;
  min-height: 0;
}

.right-column {
  height: 65%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.right-tabs {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.right-tabs :deep(.el-tabs__content) {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  min-height: 0;
}

.right-tabs :deep(.el-tab-pane) {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  min-height: 0;
}

.flex-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  min-height: 0;
}

.flex-card :deep(.el-card__body) {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  min-height: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-bar {
  margin-bottom: 16px;
  padding: 16px;
  background: white;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.pending-item {
  padding: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.3s;
  background: white;
}

.pending-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 12px rgba(64, 158, 255, 0.1);
}

.pending-item.active {
  border-color: #409eff;
  background: #f0f7ff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.pending-item-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
}

.student-basic {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.student-name {
  font-weight: 600;
  font-size: 14px;
  color: #303133;
}

.student-id {
  font-size: 12px;
  color: #909399;
}

.item-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
}

.apply-time {
  font-size: 11px;
  color: #c0c4cc;
}

.college-info {
  font-size: 12px;
  color: #606266;
  margin-bottom: 12px;
  line-height: 1.4;
}

.leave-summary {
  margin-bottom: 12px;
}

.leave-main {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 6px;
}

.leave-days {
  font-size: 13px;
  color: #e6a23c;
  font-weight: 500;
}

.time-range {
  font-size: 12px;
  color: #909399;
}

.leave-reason {
  font-size: 13px;
  color: #606266;
  line-height: 1.4;
  margin: 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.item-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.location-tags {
  display: flex;
  align-items: center;
  gap: 6px;
}

.location-text {
  font-size: 12px;
  color: #909399;
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.attachment-badge {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #909399;
  padding: 2px 6px;
  background: #f5f7fa;
  border-radius: 10px;
}

/* 详情页样式 */
.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.info-card {
  margin-bottom: 16px;
  border: 1px solid #e4e7ed;
}

.info-card :deep(.el-card__header) {
  padding: 12px 16px;
  background: #fafbfc;
  border-bottom: 1px solid #e4e7ed;
}

.info-card :deep(.el-card__body) {
  padding: 16px;
}

.card-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.info-compact {
  margin-bottom: 8px;
}

.info-compact label {
  display: block;
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.info-compact .value {
  font-size: 13px;
  color: #303133;
  line-height: 1.4;
}

.info-compact .value.highlight {
  color: #e6a23c;
  font-weight: 500;
}

.reason-text {
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 4px;
  line-height: 1.5;
}

.family-members {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.family-member {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 12px;
  background: #f8f9fa;
  border-radius: 4px;
}

.family-member .name {
  font-weight: 500;
  font-size: 13px;
}

.family-member .relation {
  font-size: 12px;
  color: #909399;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

/* 详情容器与摘要条 */
.approval-detail-card .approval-detail {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.summary-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  border-radius: 8px;
  background: #fff;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
}

.summary-left {
  font-weight: 600;
}

.summary-name {
  font-size: 14px;
}

.summary-id {
  color: #909399;
  font-size: 12px;
}

.summary-center {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
}

.summary-center .divider {
  width: 1px;
  height: 14px;
  background: #e4e7ed;
  display: inline-block;
}

.summary-center .highlight {
  color: var(--el-color-primary);
  font-weight: 600;
}

.summary-right {
  display: flex;
  gap: 8px;
}

/* 粘性操作区 */
.sticky-actions {
  position: sticky;
  bottom: 0;
  z-index: 2;
  background: #fff;
  padding: 8px 0;
  border-top: 1px solid #ebeef5;
}

/* 时间线微调 */
.timeline-item {
  padding-bottom: 8px;
}

.timeline-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

/* 历史列表样式 */
.processed-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.empty-state,
.empty-detail {
  padding: 40px 0;
  text-align: center;
}

:deep(.el-tag) {
  border: none;
  font-size: 11px;
  height: 20px;
  line-height: 18px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .equal-height-row {
    flex-direction: column;
  }

  .el-col-10,
  .el-col-14 {
    width: 100%;
  }

  .right-column {
    margin-top: 20px;
  }
}

/* 高级搜索样式 */
.header-actions {
  display: flex;
  gap: 10px;
}

.advanced-search {
  margin-bottom: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.search-actions {
  display: flex;
  justify-content: center;
  gap: 12px;
  margin-top: 8px;
}

/* 右侧布局调整 */
.top-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  margin-bottom: 16px;
}

.compact-card {
  height: fit-content;
}

.compact-card .info-compact {
  margin-bottom: 12px;
}

.time-card {
  margin-bottom: 16px;
}

.reason-content {
  padding: 12px;
  background: #f8f9fa;
  border-radius: 4px;
  line-height: 1.6;
  color: #606266;
}

/* 评论区域样式 */
.comment-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.comment-item {
  padding: 12px;
  background: #f8f9fa;
  border-radius: 4px;
  border-left: 3px solid #409eff;
}

.comment-label {
  font-size: 13px;
  font-weight: 600;
  color: #606266;
  margin-bottom: 8px;
}

.comment-content {
  font-size: 14px;
  color: #303133;
  line-height: 1.6;
  word-break: break-word;
}

/* 状态显示样式 */
.status-display {
  padding: 0;
}

.status-display :deep(.el-form-item) {
  margin-bottom: 18px;
}

.status-display :deep(.el-form-item:last-child) {
  margin-bottom: 0;
}

.status-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-icon {
  font-size: 18px;
}

.status-icon-success {
  color: #67c23a;
}

.status-icon-error {
  color: #f56c6c;
}

.status-icon-info {
  color: #909399;
}

.status-text {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
}

.status-desc {
  font-size: 14px;
  color: #606266;
}
</style>